<template>
	<view class="page-top-bg"></view>
	<AdaptiveNavBar :showBack="true" :showHome="false" :showShadow="false" text-color="#333333"
		background-color="#39b54a" />
	<view class="content-area" :style="{ marginTop: navbarTotalHeightRpx }" style="padding-top: 20rpx;">
		<view class="reply-container">
			<view class="main-content">
				<!-- 已选班期信息 -->
				<section class="section">
					<view class="section-header" style="padding: 20rpx 20rpx 20rpx 20rpx;">
						<view class="section-header__left">
							<FontIcon name="icon-xuanzebanqi" class="section-header__icon section-header__font_icon">
							</FontIcon>
							<view class="section-header__title">已选班期</view>
						</view>
						<view class="schedule-date">{{ selectedDate }}</view>
					</view>
				</section>

				<!-- 组团社联系人信息（仅组团） -->
				<section class="section" v-if="type === '组团'">
					<view class="section-header">
						<FontIcon name="icon-lianxiren" class="section-header__icon section-header__font_icon">
						</FontIcon>
						<text class="section-header__title">组团社联系人</text>
					</view>

					<view class="contact-card">
						<view class="contact-row">
							<view class="group-badge">
								<FontIcon name="icon-qizhi" color="#ffffff" />
								<text>组团</text>
							</view>
							<view class="agency-info">
								<text class="agency-name">{{ agencyName }}</text>
								<text class="play-icon">▶</text>
							</view>
							<view class="rating">
								<text class="star-icon">★</text>
								<text class="rating-value">4.8</text>
							</view>
						</view>

						<view class="contact-row">
							<text class="label">客源城市</text>
							<text class="value">{{ sourceCity }}</text>
						</view>

						<view class="contact-row">
							<view class="coordinator-badge">{{ (firstContact && firstContact.category) || '联系人'
							}}</view>
							<text class="coordinator-name">{{ (firstContact && firstContact.name) || '—' }}</text>
							<text class="coordinator-title">{{ (firstContact && firstContact.category) || '联系人'
							}}</text>
							<text class="phone-number">{{ (firstContact && firstContact.phone) || '—' }}</text>
							<FontIcon name="icon-phone" class="phone-icon" color="#39b54a" @click="makeCall" />
						</view>
					</view>
				</section>

				<!-- 随队与工作人员（仅随队） -->
				<section class="section" v-else-if="type === '随队'">
					<view class="section-header">
						<FontIcon name="icon-lianxiren" class="section-header__icon section-header__font_icon">
						</FontIcon>
						<text class="section-header__title">随队与工作人员</text>
					</view>

					<view class="contact-card">
						<view class="contact-row" v-for="(m, idx) in (periodSku.teamMembers || [])" :key="idx">
							<view class="coordinator-badge"
								style="background-color:#FBBD081A;border-color:#FBBD08;color:#FBBD08">随队</view>
							<text class="coordinator-name">{{ m.name || '—' }}</text>
							<text class="coordinator-title">{{ m.title || '' }}</text>
							<text class="phone-number">{{ m.phone || '—' }}</text>
							<FontIcon name="icon-phone" class="phone-icon" color="#39b54a" @click="makeCall(m.phone)" />
						</view>
					</view>
				</section>

				<!-- 名额申请设置：根据类型切换展示 -->
				<section class="section">
					<view class="section-header">
						<FontIcon name="icon-shenqingminge" class="section-header__icon section-header__font_icon">
						</FontIcon>
						<text class="section-header__title">答复: 名额申请</text>
					</view>

					<view class="quota-card">
						<view class="quota-item" v-if="type === '组团'">
							<view class="quota-info">
								<text class="quota-label">每团满员名额上限数</text>
								<text class="quota-value">{{ periodSku.fullNumberOfPeople || 0 }} 人</text>
							</view>
							<text class="quota-desc">报名达到该人数后,系统将限制后续报名</text>
						</view>

						<view class="quota-item" v-if="type === '组团'">
							<view class="quota-info">
								<text class="quota-label">每期最低成团人数</text>
								<text class="quota-value">{{ periodSku.leastNumberOfPeople || 0 }} 人</text>
							</view>
							<text class="quota-desc">低于该人数系统自动退费/解散行程/通知延期</text>
						</view>

						<view class="quota-item" v-if="type === '组团'">
							<view class="quota-info">
								<text class="quota-label">每期服务最大承载团数</text>
								<text class="quota-value">{{ periodSku.fullNumberOfRegiment || 0 }} 团</text>
							</view>
							<text class="quota-desc">低于该人数系统自动退费/解散行程/通知延期</text>
						</view>

						<view class="quota-item" v-if="type === '随队'">
							<view class="quota-info">
								<text class="quota-label">每小组名额上限</text>
								<text class="quota-value">{{ periodSku.groupMaxPeople || 0 }} 人</text>
							</view>
							<text class="quota-desc">每小组名额达到上限后，系统将限制报名</text>
						</view>

						<view class="quota-item" v-if="type === '随队'">
							<view class="quota-info">
								<text class="quota-label">每期名额下限</text>
								<text class="quota-value">{{ periodSku.groupMinPeople || 0 }} 人</text>
							</view>
							<text class="quota-desc">低于该人数系统可能自动退费/解散行程/通知延期</text>
						</view>
					</view>
				</section>

				<!-- 成团确认日期（共用） -->
				<section class="section">
					<view class="section-header">
						<FontIcon name="icon-chengtuanquerenriqi"
							class="section-header__icon section-header__font_icon"></FontIcon>
						<text class="section-header__title">成团确认日期</text>
					</view>

					<view class="date-card">
						<view class="date-info">
							<text class="date-label">行程日前</text>
							<text class="date-value">{{ confirmationDate.daysBeforeTrip }}天</text>
						</view>
						<view class="date-detail">
							<text class="date-text">{{ confirmationDate.date }}</text>
						</view>
					</view>
				</section>

				<!-- 接送/集散地点（仅随队） -->
				<section class="section" v-if="type === '随队'">
					<view class="section-header">
						<FontIcon name="icon-daohangbiaozhi" class="section-header__icon section-header__font_icon">
						</FontIcon>
						<text class="section-header__title">接送/集散地点</text>
					</view>

					<view class="contact-card">
						<view class="contact-row" style="border-bottom:none;margin-bottom:0;">
							<text class="value" style="flex:1">{{ periodSku.gatherArea || '—' }}</text>
							<u-icon name="map-fill" size="20" color="#1cbbb4"></u-icon>
						</view>
					</view>
				</section>

				<!-- 合作概要 -->
				<section class="section">
					<view class="section-header">
						<FontIcon name="icon-lianxiren" class="section-header__icon section-header__font_icon">
						</FontIcon>
						<text class="section-header__title">合作概要</text>
					</view>

					<view class="summary-card">
						<view class="summary-item">
							<text class="summary-label">协议签署</text>
							<text class="summary-value link" @click="viewAgreement">签署协议</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">申请时间</text>
							<text class="summary-value">{{ periodSku.applyTime }}</text>
						</view>
						<view class="summary-item">
							<text class="summary-label">申请人</text>
							<text class="summary-value">{{ periodSku.applyMan }}</text>
						</view>
					</view>
				</section>
			</view>

			<!-- 底部操作按钮 -->
			<view class="bottom-action-bar">
				<view class="action-button action-button--back" @click="goBack">
					<text class="button-text">返回</text>
				</view>
				<view class="action-button action-button--reject" @click="rejectApplication">
					<text class="button-text">驳回重提</text>
				</view>
				<view class="action-button action-button--approve" @click="approveApplication">
					<text class="button-text">同意所请</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { request } from '@/utils/request.js'
import AdaptiveNavBar from '@/components/AdaptiveNavBar.vue'

export default {
	components: {
		AdaptiveNavBar
	},
	computed: {
		// 导航栏总高度（rpx）
		navbarTotalHeightRpx() {
			if (this.$navbarUtil && this.$navbarUtil.getNavbarTotalHeightRpx) {
				return this.$navbarUtil.getNavbarTotalHeightRpx()
			}
			// 如果 $navbarUtil 不可用，返回默认值
			return '176rpx' // 默认 88px * 2 = 176rpx
		},
		// 首位联系人（组团）
		firstContact() {
			const list = this.periodSku && Array.isArray(this.periodSku.contact) ? this.periodSku.contact : []
			return list && list.length > 0 ? list[0] : null
		}
	},
	data() {
		return {
			statusBarHeight: 0,
			selectedDate: '2025年01月11日',
			replyType: '',
			replyContent: '',
			callApplyId: '', // 申请表ID
			agencyName: '', // 客源机构名称
			sourceCity: '',// 客源城市
			date: '',// 申请日期
			type: '',//客源机构类型
			periodSku: {},// 申请的班期SKU
			confirmationDate: {}
		}
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},

		selectReplyType(type) {
			this.replyType = type
		},

		makeCall(phone) {
			const target = phone || (this.firstContact && this.firstContact.phone) || ''
			if (!target) {
				uni.showToast({ title: '暂无联系电话', icon: 'none' })
				return
			}
			uni.showModal({
				title: '拨打电话',
				content: `确定要拨打 ${target} 吗？`,
				success: (res) => {
					if (res.confirm) {
						console.log('拨打电话:', target)
					}
				}
			})
		},

		submitReply() {
			if (!this.replyType) {
				uni.showToast({ title: '请选择答复类型', icon: 'none' })
				return
			}

			uni.showModal({
				title: '确认答复',
				content: `确定要${this.replyType === 'agree' ? '同意' : '拒绝'}此申请吗？`,
				success: (res) => {
					if (res.confirm) {
						this.submitApplicationReply()
					}
				}
			})
		},

		// 驳回申请
		rejectApplication() {
			//填写驳回内容
			uni.showModal({
				title: '驳回申请',
				content: '请输入驳回原因',
				editable: true,
				placeholderText: '请填写具体驳回理由',
				success: (res) => {
					if (res.confirm) {
						this.replyType = 'reject'
						//驳回原因
						this.replyContent = res.content || '拒绝申请'
						this.submitApplicationReply()
					}
				}
			})
		},

		// 同意申请
		approveApplication() {
			uni.showModal({
				title: '同意申请',
				content: '确定要同意此申请吗？',
				success: (res) => {
					if (res.confirm) {
						this.replyType = 'agree'
						this.replyContent = '同意申请'
						this.submitApplicationReply()
					}
				}
			})
		},

		// 查看协议
		viewAgreement() {
			console.log('查看协议')
			uni.showModal({
				title: '协议详情',
				content: '境内研学接团协议\n\n这里可以显示协议的详细内容...',
				showCancel: false,
				confirmText: '确定'
			})
		},

		// 加载申请班期详情数据
		async loadApplicationDetail() {
			try {
				//根据getBycallApplyId 查申请的班期信息
				const res = await request({
					url: '/period-sku/getBycallApplyId',
					method: 'GET',
					data: { callApplyId: this.callApplyId }
				})
				console.log('申请班期详情数据', res.data)
				if (res.code === 200) {
					this.periodSku = res.data
					console.log('申请班期详情', this.periodSku)
					this.syncFromSku()
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
				console.log('加载申请班期详情:', this.periodSku)

			} catch (error) {
				console.error('加载申请详情失败:', error)
				uni.showToast({ title: '加载失败', icon: 'none' })
			}
		},

		// 从 periodSku 同步页面展示所需字段（有则用 periodSku，没有保留原值）
		syncFromSku() {
			try {
				const d = this.periodSku || {}
				// 1) 成团确认：仅在 periodSku 提供值时覆盖
				if (d.confirmationTime !== undefined && d.confirmationTime !== null) {
					const days = Number(d.confirmationTime)
					if (!isNaN(days)) {
						this.confirmationDate.daysBeforeTrip = days
					}
				}
				// 2) 依据 availableDate 计算确认日期、selectedDate（仅在提供完整日期时覆盖）
				const ad = d.availableDate || {}
				const y = Number(ad.yearDate)
				const m = Number(ad.monthDate)
				const day = Number(ad.dayDate)
				if (!isNaN(y) && !isNaN(m) && !isNaN(day)) {
					// selectedDate 优先用 periodSku 的行程日
					this.selectedDate = `${y}年${String(m).padStart(2, '0')}月${String(day).padStart(2, '0')}日`

					// 确认日期 = 行程日前 N 天（N 使用当前已确定的 daysBeforeTrip）
					const tripDate = new Date(y, (m - 1), day)
					const confirm = new Date(tripDate)
					confirm.setDate(tripDate.getDate() - (this.confirmationDate.daysBeforeTrip || 0))
					const yy = confirm.getFullYear()
					const mm = String(confirm.getMonth() + 1).padStart(2, '0')
					const dd = String(confirm.getDate()).padStart(2, '0')
					this.confirmationDate.date = `${yy}年${mm}月${dd}日`
				}
				// 其余展示字段均在模板中以 periodSku 优先、静态/传参为备选的方式渲染
			} catch (e) {
				console.warn('同步 periodSku 展示字段失败:', e)
			}
		},

		// 提交申请答复
		async submitApplicationReply() {
			try {
				// 调用答复申请的接口
				const res = await request({
					url: '/call-apply/handle',
					method: 'POST',
					data: {
						applyId: this.callApplyId,
						status: this.replyType === 'agree' ? 1 : 2,
						reply: this.replyContent
					}
				})

				if (res.code === 200) {
					console.log('答复申请成功:', {
						applyId: this.callApplyId,
						replyType: this.replyType,
						replyContent: this.replyContent
					})

					// 通知上一页刷新数据
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					if (prevPage) {
						// 获取上一页选中的班期信息
						const selectedPeriod = prevPage.selectedDates && prevPage.selectedDates.find(item => item.isSelected)
						if (selectedPeriod && selectedPeriod.periodId && prevPage.loadPeriodApplications) {
							// 构建完整的日期显示
							const dateParts = selectedPeriod.DateName ? selectedPeriod.DateName.split('-') : []
							const fullDate = dateParts.length >= 3 ?
								`${dateParts[0]}年${dateParts[1]}月${dateParts[2]}日` :
								(selectedPeriod.DateName || '--')
							// 调用上一页的刷新方法
							prevPage.loadPeriodApplications(selectedPeriod.periodId, fullDate)
							console.log('✅ 已通知上一页刷新申请列表')
						}
					}

					uni.showToast({
						title: '答复成功',
						icon: 'success',
						success: () => {
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						}
					})
				} else {
					console.error('答复申请失败:', res.message)
					uni.showToast({
						title: res.message || '答复失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('提交申请答复失败:', error)
				uni.showToast({ title: '答复失败', icon: 'none' })
			}
		},
	},
	onLoad(options) {
		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync()
		this.statusBarHeight = systemInfo.statusBarHeight || 20

		console.log('答复申请页面接收参数', options)
		// 获取传递的参数（兼容 relationId 和 callApplyId 两种命名）
		if (options.callApplyId) {
			this.callApplyId = options.callApplyId
		} else if (options.relationId) {
			this.callApplyId = options.relationId
		}
		if (options.date) {
			this.selectedDate = decodeURIComponent(options.date)
		}
		if (options.agencyName) {
			this.agencyName = options.agencyName
		}
		if (options.sourceCity) {
			this.sourceCity = options.sourceCity
		}
		if (options.type) {
			this.type = options.type
		}
		// 加载申请班期数据
		this.loadApplicationDetail()
	},
	onShow() {
		try {
			const pages = getCurrentPages()
			const cur = pages[pages.length - 1] || {}
			const opts = (cur && cur.options) || {}
			console.log('页面onShow，当前路由与参数', { route: cur.route, options: opts })
		} catch (e) {
			console.warn('onShow 获取参数失败')
		}
	}
}
</script>

<style lang="scss" scoped>
// 全局变量定义
$primary-color: #39b54a; // 主题绿，贴近设计稿
$secondary-color: #82A0F7;
$danger-color: #FF3B30;
$warning-color: #FC642F;
$success-color: #4CAF50;
$gray-color: #8E8E93;
$light-gray: #F1F1F1;
$border-color: #EEEEEE;
$text-primary: #333333;
$text-secondary: #999999;
$text-light: #FFFFFF;
$radius-base: 12rpx;
$radius-large: 20rpx;
$shadow-sm: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
$shadow-md: 0rpx -4rpx 14rpx 0rpx rgba(241, 241, 241, 0.5);
$transition-base: all 0.3s ease;

.page-top-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 750rpx;
	height: 280rpx;
	background: #39b54a;
	box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(216, 216, 216, 0.72);
	backdrop-filter: blur(0px);
	pointer-events: none; // 不拦截点击
}

.content-area {
	background: #eeeeee;
}

.reply-container {
	position: relative;
	min-height: 100vh;
}

.main-content {
	padding-bottom: 180rpx;
}

// 通用区块样式
.section {
	background: #ffffff;
	margin: 24rpx;
	border-radius: 20rpx;

	&-header {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		padding: 28rpx;

		&__left {
			display: flex;
			align-items: center;
			flex: 1;
		}

		&__icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 20rpx;
			font-size: 24rpx;
			color: #787878;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #f2f2f2;
			border-radius: 4rpx;
		}

		&__title {
			font-size: 28rpx;
			font-weight: 600;
			color: #333333;
		}

		&__font_icon {
			color: #787878;
		}
	}

	&-description {
		font-size: 24rpx;
		color: $text-secondary;
		padding: 0rpx 28rpx 20rpx;
		line-height: 1.5;
	}
}

.schedule-date {
	font-size: 28rpx;
	color: $primary-color;
	font-weight: 600;
	margin-right: 20rpx;
}

.contact-card {
	padding: 0rpx 28rpx 20rpx;
}

.contact-row {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	padding: 0rpx 0rpx 20rpx;
	border-bottom: 1rpx dashed #eee;
}

.contact-row:last-child {
	margin-bottom: 0;
	border-bottom: none;
}

.group-badge {
	width: 120rpx;
	height: 56rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 6rpx;
	background-color: #39B54A;
	color: #ffffff;
	border: 1rpx solid #39B54A;
	border-radius: 15rpx;
	font-size: 24rpx;
	text-align: center;
	box-sizing: border-box;
	margin-right: 15rpx;
}

.agency-info {
	display: flex;
	align-items: center;
	flex: 1;
}

.agency-name {
	font-size: 28rpx;
	color: #333333;
	font-weight: 600;
	margin-right: 8rpx;
}

.play-icon {
	font-size: 16rpx;
	color: #333333;
}

.rating {
	display: flex;
	align-items: center;
	margin-left: 16rpx;
}

.star-icon {
	font-size: 28rpx;
	color: #FFD700;
	margin-right: 6rpx;
}

.rating-value {
	font-size: 24rpx;
	color: #333333;
	font-weight: 600;
	line-height: 1;
}

.label {
	font-size: 28rpx;
	color: #999999;
	margin-right: 15rpx;
}

.value {
	font-size: 28rpx;
	color: #333333;
}

.coordinator-badge {
	background-color: rgba(252, 100, 47, 0.1);
	color: #FC642F;
	border: 1rpx solid #FC642F;
	border-radius: 4rpx;
	padding: 4rpx 12rpx;
	font-size: 20rpx;
	font-weight: 600;
	margin-right: 16rpx;
}

.coordinator-name {
	font-size: 24rpx;
	color: #333333;
	margin-right: 8rpx;
}

.coordinator-title {
	font-size: 20rpx;
	color: #FC642F;
	margin-right: 16rpx;
}

.phone-number {
	font-size: 24rpx;
	color: #000000;
	font-weight: 600;
	margin-right: 8rpx;
}

.phone-icon {
	font-size: 24rpx;
	color: $primary-color;
}

.quota-card {
	padding: 0rpx 28rpx 20rpx;
}

.quota-item {
	margin-bottom: 24rpx;
	padding-bottom: 24rpx;
	border-bottom: 1rpx dashed #eee;
}

.quota-item:last-child {
	margin-bottom: 0;
	padding-bottom: 0;
	border-bottom: none;
}

.quota-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.quota-label {
	font-size: 28rpx;
	color: #000000;
	font-weight: 500;
}

.quota-value {
	font-size: 28rpx;
	color: #333333;
	font-weight: 600;
}

.quota-desc {
	font-size: 24rpx;
	color: $text-secondary;
	line-height: 1.5;
}

.date-card {
	padding: 0rpx 28rpx 20rpx;
}

.date-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
	padding-bottom: 12rpx;
	border-bottom: 1rpx dashed #eee;
}

.date-label {
	font-size: 28rpx;
	color: #000000;
	font-weight: 500;
}

.date-value {
	font-size: 28rpx;
	color: #333333;
	font-weight: 600;
}

.date-detail {
	margin-top: 8rpx;
}

.date-text {
	font-size: 24rpx;
	color: $text-secondary;
}

.summary-card {
	padding: 0rpx 28rpx 20rpx;
}

.summary-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
	padding-bottom: 16rpx;
	border-bottom: 1rpx dashed #eee;
}

.summary-item:last-child {
	margin-bottom: 0;
	padding-bottom: 0;
	border-bottom: none;
}

.summary-label {
	font-size: 28rpx;
	color: $text-secondary;
}

.summary-value {
	font-size: 28rpx;
	color: #333333;
	font-weight: 600;
}

.summary-value.link {
	color: #0081ff;
	text-decoration: underline;
}

/* 底部操作栏 */
.bottom-action-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: calc(110rpx + env(safe-area-inset-bottom));
	background: white;
	border-top: 1rpx solid #f2f2f2;
	padding: 12rpx 24rpx calc(12rpx + env(safe-area-inset-bottom)) 24rpx;
	display: flex;
	gap: 16rpx;
	align-items: center;
	z-index: 100;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.action-button {
	/* 胶囊形状关键：设置足够大的圆角 */
	border-radius: 100rpx;
	/* 或使用 50rpx 以上，推荐 100rpx 更圆润 */
	padding: 14rpx 0;
	/* 水平内边距设为 0，避免文字被挤压 */
	text-align: center;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	transition: all 0.3s ease;
	min-height: 70rpx;
}

.action-button--back {
	flex: 0.8;
	background: #F5F5F5;
}

.action-button--back .button-text {
	color: #999999;
	font-weight: 500;
}

.action-button--reject {
	flex: 1.1;
	background: #FF3B30;
	box-shadow: 0 4rpx 12rpx rgba(255, 59, 48, 0.3);
}

.action-button--reject:active {
	transform: scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
}

.action-button--approve {
	flex: 1.1;
	background: #39b54a;
	box-shadow: 0 4rpx 12rpx rgba(57, 181, 74, 0.3);
}

.action-button--approve:active {
	transform: scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(57, 181, 74, 0.3);
}

.button-text {
	font-size: 28rpx;
	color: #FFFFFF;
	font-weight: 600;
	line-height: 1.2;
}
</style>
